<template>
    <uni-popup ref="mediaPopup" type="bottom">
        <view class="media-picker">
            <view class="picker-header">
                <text class="title">选择媒体类型</text>
                <text class="close" @click="handleClose">×</text>
            </view>


            <!-- 添加拖拽上传区域 -->
            <div class="upload-area" :class="{ 'is-dragging': isDragging }" @dragover.prevent="handleDragOver"
                @dragleave.prevent="handleDragLeave" @drop.prevent="handleDrop">
                <text class="upload-text">拖拽文件到此处</text>
            </div>

            <view class="options">
                <view class="option-item" @click="handleChooseImage">
                    <uni-icons type="image" size="30" color="#409eff"></uni-icons>
                    <text>选择图片</text>
                </view>

                <view class="option-item" @click="handleChooseVideo">
                    <uni-icons type="videocam" size="30" color="#f56c6c"></uni-icons>
                    <text>选择视频</text>
                </view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
    // 可以添加配置项
    imageConfig: {
        type: Object,
        default: () => ({
            count: 9,
            sourceType: ['album', 'camera'],
            sizeType: ['original']
        })
    },
    videoConfig: {
        type: Object,
        default: () => ({
            sourceType: ['album', 'camera'],
            compressed: false
        })
    }
})

const emit = defineEmits(['select'])
const mediaPopup = ref(null)
const isDragging = ref(false)

// 打开选择器
const open = () => {
    mediaPopup.value.open()
}

// 关闭选择器
const handleClose = () => {
    mediaPopup.value.close()
}


// 添加拖拽相关方法
const handleDragOver = (e) => {
    e.preventDefault()
    isDragging.value = true
}

const handleDragLeave = (e) => {
    e.preventDefault()
    isDragging.value = false
}

const handleDrop = async (e) => {
    e.preventDefault()
    e.stopPropagation()
    isDragging.value = false

    if (!e.dataTransfer) {
        emit('error', '无效的拖拽操作')
        return
    }

    const list = Array.from(e.dataTransfer.files || [])
    if (list.length === 0) {
        emit('error', '未检测到有效文件')
        return
    }

    const files = list.map(file => ({
        path: file.path || file.url, // H5环境使用url
        name: file.name || getFileNameFromPath(file.path || file.url),
        size: file.size,
        type: 'image',
        file: file
    }))
    console.log("files", files);

    emit('select', files)
}


// 选择图片
const handleChooseImage = () => {
    handleClose()
    setTimeout(async () => {
        try {
            const res = await uni.chooseImage(props.imageConfig)
            if (res.tempFiles && res.tempFiles.length > 0) {
                const files = res.tempFiles.map(file => ({
                    path: file.path || file.url, // H5环境使用url
                    name: file.name || getFileNameFromPath(file.path || file.url),
                    size: file.size,
                    type: 'image',
                    // H5环境需要保存file对象用于读取
                    // #ifdef H5
                    file: file,
                    // #endif
                }))
                console.log("files", files);

                emit('select', files)
            }
        } catch (error) {
            handleError(error)
        }
    }, 200)
}

// 选择视频
const handleChooseVideo = () => {
    handleClose()
    setTimeout(async () => {
        try {
            const res = await uni.chooseVideo(props.videoConfig)
            emit('select', [{
                path: res.tempFilePath,
                name: res.name || `video_${Date.now()}.mp4`,
                size: res.size,
                type: 'video',
                // H5环境需要保存file对象
                // #ifdef H5
                file: new File([res.tempFile], res.name || `video_${Date.now()}.mp4`, {
                    type: 'video/mp4'
                }),
                // #endif
            }])
        } catch (error) {
            handleError(error)
        }
    }, 200)
}

// 错误处理
const handleError = (error) => {
    console.error('选择文件失败:', error)
    uni.showToast({
        title: '选择文件失败',
        icon: 'none'
    })
}

// 工具方法：从路径获取文件名
const getFileNameFromPath = (path) => {
    return path.split('/').pop().split('?')[0]
}

// 暴露方法给父组件
defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.media-picker {
    background: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 40rpx;

    .picker-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 40rpx;

        .title {
            font-size: 36rpx;
            font-weight: bold;
        }

        .close {
            font-size: 50rpx;
            color: #999;
        }
    }

    .options {
        display: flex;
        justify-content: space-around;
        gap: 40rpx;

        .option-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20rpx;
            border-radius: 16rpx;
            width: 200rpx;
            border: 2rpx solid #eee;
            flex: 1;
            text {
                margin-top: 16rpx;
                font-size: 28rpx;
            }
        }
    }

    // 添加拖拽区域样式
    .upload-area {
        border: 2rpx dashed #ddd;
        padding: 100rpx 40rpx;
        text-align: center;
        border-radius: 16rpx;
        transition: all 0.3s;
        background: #f8f8f8;
        margin-bottom: 40rpx;

        &.is-dragging {
            border-color: #409eff;
            background: rgba(64, 158, 255, 0.05);
        }
    }

    .upload-text {
        color: #666;
        font-size: 28rpx;
        display: block;
    }
}
</style>